/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
    struct cmp
    {
        bool operator()(ListNode* l1, ListNode* l2)
        {
            return l1->val > l2->val;
        }
    };
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*, vector<ListNode*>, cmp> pq;
        for (auto l : lists)
            if (l)
                pq.push(l);

        ListNode* ret = new ListNode(0);
        ListNode* cur = ret;

        while (pq.size())
        {
            ListNode* t = pq.top();
            if (t->next) pq.push(t->next);
            pq.pop();
            cur->next = t;
            cur = cur->next;
        }

        return ret->next;
    }
};
